package com.motu.monstercity.server.game.logichandler;

import com.motu.monstercity.module.common.iap.IapGift;
import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.Common.PBUserDecorate;
import com.motu.monstercity.protocol.Common.PBUserDetailInfo;
import com.motu.monstercity.protocol.Common.PBUserItem;
import com.motu.monstercity.protocol.CsGameGameuser.*;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.build.BuildConstant;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.system.*;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.log.MotuLogManager;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.SensitivewordEngine;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.ext.sync.Sync;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class GameuserHandler {
	// CMD_GAME_GAMEUSER_CHANGE_NAME = 70401; // 改名
	public static Object CMD_GAME_GAMEUSER_CHANGE_NAME(RequestParam clientParam) throws Exception {
		CSGameGameuserChangeNameRequest request = CSGameGameuserChangeNameRequest.parseFrom(clientParam.getData());
		CSGameGameuserChangeNameResponse.Builder response = CSGameGameuserChangeNameResponse.newBuilder();
		long userId = clientParam.getUserId();

		UserInfo userInfo = GameUser.getUserInfo(userId);
		String name = request.getName();

		String roleName = Tool.dropFourByte(name);//将字符串中的苹果表情符过滤掉
		ErrorWord errorWord = CommonUtils.checkString(roleName, AllParam.SYSTEM_NAME_WORDSNUM[0], AllParam.SYSTEM_NAME_WORDSNUM[1], false);// 最小2个字符,最大14个字符,7个字
		if (errorWord != ErrorWord.SUCCESS) {
			return errorWord;
		}

		if (roleName == null || roleName.length() == 0) {
			return ErrorWord.BAD_PARAM;//没有东西要修改
		}

		int itemId = ItemId.CARD_CHANGE_NAME;// 优先使用改名卡
		long subNum = 1;// 改名卡扣一张
		long userItemNum = BagManager.getUserItemNum(userInfo, itemId);
		if (userItemNum < subNum) {
			itemId = ItemId.DIAMOND;// 无改名卡则用钻石
			subNum = AllParam.BUILD_CHANGE_NAME_DIAMOND_NUM;
		}
		userItemNum = BagManager.getUserItemNum(userInfo, itemId);// 判断钻石数量
		if (userItemNum < subNum) {
			return ErrorWord.ITEM_LACK;//
		}

		boolean hasEngChar = Tool.checkEngChar(roleName);
		String sql1 = "";
		if (hasEngChar)
			sql1 = "select 1 from user_info where  lower(user_name) = lower(?) and server_id = ? limit 1;";
		else
			sql1 = "select 1 from user_info where  user_name = ? and server_id = ? limit 1;";
		JsonArray params1 = new JsonArray();
		params1.add(roleName);
		params1.add(userInfo.getServerId());
		String sql = sql1;
		JsonObject jsonObject = Future.await(MysqlTool.queryJsonObjectFromDb(MysqlClient.getGamePool(), sql, params1));
		if (jsonObject != null && !jsonObject.isEmpty()) {
			return ErrorWord.WRONG_STATUS;//名字已经被用了
		}

		// 检测敏感字（先进行重名校验，在进行敏感词检测，防止重复刷文字校验api）
		String tempName = roleName;
		UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
		try {
			roleName = SensitivewordEngine.replaceNameBySdk(roleName, userExtInfo.getPlatform());
		} catch (Exception e){
			return ErrorWord.BAD_WORD;
		}
		if (!tempName.equals(roleName)) {
			return ErrorWord.BAD_WORD;// 有敏感字
		}

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		RewardManager.subReward(userInfo, itemId, subNum, pbUserData, LogType.BUILD_CHANGE_NAME);
		userInfo.putUserName(roleName);
		userInfo.updateNow();
		ProtoDataUtils.updatePBUserData(pbUserData, userInfo);

		return response;
	}

	//CMD_GAME_GAMEUSER_EXCHANGE_GIFT = 70402; // 使用兑换码
	public static Object CMD_GAME_GAMEUSER_EXCHANGE_GIFT(RequestParam clientParam) throws Exception {
		CSGameGameuserExchangeGiftRequest request = CSGameGameuserExchangeGiftRequest.parseFrom(clientParam.getData());
		CSGameGameuserExchangeGiftResponse.Builder response = CSGameGameuserExchangeGiftResponse.newBuilder();
		long userId = clientParam.getUserId();

		String key = request.getKey();// 兑换码
		if (Tool.isEmpty(key)) {
			return ErrorWord.BAD_PARAM;
		}
		String key2 = Tool.dropFourByte(key);
		if  (!key2.equalsIgnoreCase(key)){
			return ErrorWord.CHAR_NOT_ALLOW;
		}

		key = key.toLowerCase();// 兑换码转成小写
		String sql = "SELECT * FROM activities_gift WHERE random_str = ? limit 1;";
		JsonArray params = new JsonArray();
		params.add(key);
		JsonArray array = Future.await(MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql, params));
		if (array == null || array.size() == 0) {
			return ErrorWord.ITEM_NOT_EXIST;
		}

		JsonObject obj = array.getJsonObject(0);
		int status = obj.getInteger("status");
		if (status == 1) {//已经被使用过了
			return ErrorWord.WRONG_STATUS;//已经领取过的兑换码
		}
		long endTime = obj.getLong("end_time");
		if (endTime > 0 && TimeUtils.getCurTime() > endTime) {
			return ErrorWord.INVALID_OPERATION;//兑换码过期了
		}

		// 条件限制
		UserInfo userInfo = GameUser.getUserInfo(userId);
		UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
		if (obj.containsKey("platform")) {
			int platform = obj.getInteger("platform");
			if (platform != 0 && userExtInfo.getPlatform() != platform) {
				return ErrorWord.ENTITY_NOT_EXIST;// 不是指定的platform
			}
		}
		
		if (obj.containsKey("ext_type") && obj.containsKey("ext_param")) {
			int exttype = obj.getInteger("ext_type"); //条件类型:   1:vip等级>=,2玩家等级<=,3玩家等级>=
			int extparam = obj.getInteger("ext_param"); //条件参数
			if (exttype == 1) {
				// Vip等级限制
				if (userInfo.getVip() < extparam) {
					return ErrorWord.VIP_LACK;
				}
			} else if (exttype == 2) {
				// 等级小于等于
				// 等级超过
				if (userInfo.getLevel() > extparam) {
					return ErrorWord.LEVEL_LACK;
				}
			} else if (exttype == 3) {
				// 等级大于等于
				// 等级不足
				if (userInfo.getLevel() < extparam) {
					return ErrorWord.LEVEL_LACK;
				}
			}
			//后期需要什么条件类型往下加
		}

		int repeatUseType = obj.getInteger("repeat_use");//  兑换码重复使用的类型
		String addTag = obj.getString("add_tag");// 批次标识
		if (repeatUseType == SystemConstant.ACTIVITIES_GIFT_USE_TYPE_0) {//同一批的兑换码，同一个Userid只能领取一次
			String sql2 = "SELECT 1 FROM activities_gift WHERE user_id = ? and add_tag = ? limit 1;";
			JsonArray params2 = new JsonArray();
			params2.add(userId);
			params2.add(addTag);
			JsonArray array2 = Future.await(MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql2, params2));
			if (array2 != null && array2.size() > 0) {
				return ErrorWord.REPEATED_OPERATION;//同一批的兑换码不能领取两次
			}
		} else if (repeatUseType == SystemConstant.ACTIVITIES_GIFT_USE_TYPE_2) {// 可以共用的兑换,不会更新status,一个用户领取一次
			String sql2 = "SELECT 1 FROM user_cdkey WHERE lower(cdkey) = ? and user_id = ?;";
			JsonArray params2 = new JsonArray();
			params2.add(key);
			params2.add(userId);
			JsonArray array2 = Future.await(MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql2, params2));
			if (array2 != null && array2.size() > 0) {
				return ErrorWord.REPEATED_OPERATION;//同一个的兑换码不能领取两次
			}
		}

		String userName = userInfo.getUserName();
		int sqlUpdateNum = 0;//数据库更新成功条数
		String sql3 = "";
		JsonArray params3 = new JsonArray();
		if (repeatUseType == SystemConstant.ACTIVITIES_GIFT_USE_TYPE_2) {//可以共用的兑换,不会更新status,一个用户领取一次,领用记录
			sql3 = "insert into user_cdkey(cdkey, user_id, user_name, add_time) values(?,?,?,?);";
			params3.add(key);
			params3.add(userId);
			params3.add(userName);
			params3.add(TimeUtils.getCurTime());
		} else {
			sql3 = "update activities_gift set user_id = ?,user_name = ?,get_time=?,status=1 where random_str = ? and status = 0;";
			params3.add(userId);
			params3.add(userName);
			params3.add(TimeUtils.getCurTime());
			params3.add(key);
		}
		try {
			Future.await(MysqlTool.updateToDb(MysqlClient.getServerPool(), sql3, params3));
		} catch (Exception e) {}

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		List<RewardItem> list = MailManager.takeRewardItem(obj.getString("item"));
		if (list != null && list.size() > 0) {
			RewardManager.addReward(userInfo, list, pbUserData, LogType.ACTIVITIES_GIFT_REWARD, key);
		}

		return response;
	}

	// CMD_GAME_GAMEUSER_SET_DECORATE = 70403; // 玩家设置头像,头像框,称号,聊天气泡等装饰类道具
	public static Object CMD_GAME_GAMEUSER_SET_DECORATE(RequestParam clientParam) throws Exception {
		CSGameGameuserSetDecorateRequest request = CSGameGameuserSetDecorateRequest.parseFrom(clientParam.getData());
		CSGameGameuserSetDecorateResponse.Builder response = CSGameGameuserSetDecorateResponse.newBuilder();
		long userId = clientParam.getUserId();

		int decorateId = request.getDecorateId();
		int type = request.getType();

		if (decorateId > 0) {
			DecorateMain decorateMain = GameDataManager.getDecorateMain(decorateId);
			if (decorateMain == null || decorateMain.getType() != type) {
				return ErrorWord.NOT_DATA;
			}
			UserDecorate userDecorate = GameDataManager.getUserDecorate(userId, decorateId);
			if (userDecorate == null) {
				return ErrorWord.ITEM_LACK;// 未获得
			}
			if (type == GameDataManager.DECORATE_TYPE_3) {// 称号要判断是否已经激活且未到期
				UserTitle userTitle = GameDataManager.getUserTitle(userId, decorateId);
				if (userTitle == null || userTitle.isExpired(TimeUtils.getCurTime())) {
					return ErrorWord.WRONG_STATUS;// 已经过期
				}
			}
		}

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		boolean isUpdate = false;
		if (type == GameDataManager.DECORATE_TYPE_1) {// 为头像，配置id为601001~601999
			userInfo.putIcon(decorateId + "");
			isUpdate = true;
			MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_54, 1);// 更新主线任务,成就,日常任务的进度
			RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_54, 1);
		} else if (type == GameDataManager.DECORATE_TYPE_2) {// 2为头像框，配置id为602001~602999 头像框没有到期时间，不会过期
			userInfo.putIconFrame(decorateId);
			isUpdate = true;
		} else if (type == GameDataManager.DECORATE_TYPE_3) {// 称号
			userInfo.putTitleId(decorateId);
			isUpdate = true;
		}

		if (isUpdate) {
			userInfo.update();
			ProtoDataUtils.updatePBUserData(pbUserData, userInfo);
		}

		return response;
	}

	// CMD_GAME_GAMEUSER_SET_TEACHID = 70404; // 设置玩家的教学id
	public static Object CMD_GAME_GAMEUSER_SET_TEACHID(RequestParam clientParam) throws Exception {
		CSGameGameuserSetTeachidRequest request = CSGameGameuserSetTeachidRequest.parseFrom(clientParam.getData());
		CSGameGameuserSetTeachidResponse.Builder response = CSGameGameuserSetTeachidResponse.newBuilder();
		long userId = clientParam.getUserId();

		int teachId = request.getTeachId();

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
//		if (userExtInfo.getTeachId() == 0) {// 第一次设置引导id 的时候获得3个人口
//			UserInfo userInfo = GameUser.getUserInfo(userId);
//			RewardManager.addReward(userInfo, ItemId.PERSON, 3, pbUserData, LogType.SYSTEM_REWARD);
//		}
		if (teachId != userExtInfo.getTeachId()) {
			userExtInfo.putTeachId(teachId);
			userExtInfo.update();
			ProtoDataUtils.updatePBUserData(pbUserData, userExtInfo);
		}

		return response;
	}

	// CMD_GAME_GAMEUSER_CHECK_INFO = 70405; // 查看某个玩家的详细信息
	public static Object CMD_GAME_GAMEUSER_CHECK_INFO(RequestParam clientParam) throws Exception {
		CSGameGameuserCheckInfoRequest request = CSGameGameuserCheckInfoRequest.parseFrom(clientParam.getData());
		CSGameGameuserCheckInfoResponse.Builder response = CSGameGameuserCheckInfoResponse.newBuilder();

		long targetId = request.getTargetId();//

		// 执行逻辑
		UserInfo userInfo = GameUser.getUserInfo(targetId);
		if (userInfo != null) {
			PBUserDetailInfo.Builder builder = GameUser.takeUserDetailInfoBuilder(targetId);
			response.setDetailInfo(builder);
		} else {
			return ErrorWord.ENTITY_NOT_EXIST;
		}

		return response;
	}

	// CMD_GAME_GAMEUSER_DECORATE_MAIN_INFO = 70406; // 下发装饰类道具,头像列表,头像框列表 ([1]第一次请求)
	public static Object CMD_GAME_GAMEUSER_DECORATE_MAIN_INFO(RequestParam clientParam) throws Exception {
		CSGameGameuserDecorateMainInfoRequest request = CSGameGameuserDecorateMainInfoRequest.parseFrom(clientParam.getData());
		CSGameGameuserDecorateMainInfoResponse.Builder response = CSGameGameuserDecorateMainInfoResponse.newBuilder();
		long userId = clientParam.getUserId();

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		for (UserDecorate userDecorate : GameDataManager.getUserDecorateList(userId)) {
			if (userDecorate.getNum() > 0) {
				ProtoDataUtils.updatePBUserData(pbUserData, userDecorate, true);
			}
		}
		for (UserTitle userTitle : GameDataManager.getUserTitleList(userId)) {
			if (!userTitle.isExpired(TimeUtils.getCurTime())) {
				ProtoDataUtils.updatePBUserData(pbUserData, userTitle, true);
			}
		}

		return response;
	}


	// CMD_GAME_GAMEUSER_GET_TEACH_REWARD = 70407; // 领取引导的特殊奖励,市政中心达到3级获得秘书爱丽丝
	public static Object CMD_GAME_GAMEUSER_GET_TEACH_REWARD(RequestParam clientParam) throws Exception {
		CSGameGameuserGetTeachRewardRequest request = CSGameGameuserGetTeachRewardRequest.parseFrom(clientParam.getData());
		CSGameGameuserGetTeachRewardResponse.Builder response = CSGameGameuserGetTeachRewardResponse.newBuilder();
		long userId = clientParam.getUserId();

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		UserBuild userBuild = BuildManager.getUserBuild(userId, BuildConstant.BUILD_ID_CITY_CENTER);
		if (userBuild != null && userBuild.getLevel() >= AllParam.TEACH_REWARD_PARTNER[0]) {
			RewardManager.addReward(userInfo, AllParam.TEACH_REWARD_PARTNER[1], 1, pbUserData, LogType.SYSTEM_REWARD);
		}
		if (userBuild != null && userBuild.getLevel() >= AllParam.TEACH_REWARD_SECR[0]) {
			RewardManager.addReward(userInfo, AllParam.TEACH_REWARD_SECR[1], 1, pbUserData, LogType.SYSTEM_REWARD);
		}

		return response;
	}


	// CMD_GAME_GAMEUSER_GET_SYSTEM_OPEN_REWARD = 70408; // 领取系统模块的解锁奖励
	public static Object CMD_GAME_GAMEUSER_GET_SYSTEM_OPEN_REWARD(RequestParam clientParam) throws Exception {
		CSGameGameuserGetSystemOpenRewardRequest request = CSGameGameuserGetSystemOpenRewardRequest.parseFrom(clientParam.getData());
		CSGameGameuserGetSystemOpenRewardResponse.Builder response = CSGameGameuserGetSystemOpenRewardResponse.newBuilder();
		long userId = clientParam.getUserId();

		int systemOpenId = request.getSystemOpenId();// 系统模块的id
		SystemOpen systemOpen = GameDataManager.getSystemOpen(systemOpenId);
		if (systemOpen == null || systemOpen.getType() != 1 || Tool.isEmpty(systemOpen.getReward())) {
			return ErrorWord.NOT_DATA;// 不是系统模块，或是无配置解锁奖励
		}

		UserAffair userAffair = GameUser.getUserAffair(userId);
		JsonArray jsonArray = userAffair.getSystemOpenRewardArray();// 领取记录
		if (Tool.isInList(jsonArray, systemOpenId)) {
			return ErrorWord.REPEATED_OPERATION;// 重复领取
		}

		UserInfo userInfo = GameUser.getUserInfo(userId);
		UserStage userStage = FightManager.getUserStage(userId);
		if (!SystemManager.checkModuleOpen(userInfo, userAffair, userStage, systemOpenId)) {
			return ErrorWord.WRONG_STATUS;// 条件未达到
		}

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		RewardManager.addReward(userInfo, CommonUtils.takeReawrdItemFromStr(systemOpen.getReward()), pbUserData, LogType.SYSTEM_OPEN_REWRD, systemOpenId);
		jsonArray.add(systemOpenId);
		userAffair.putSystemOpenReward(jsonArray.toString());
		userAffair.update();
		ProtoDataUtils.updatePBUserData(pbUserData, userAffair);

		return response;
	}


	// CMD_GAME_GAMEUSER_ADVIDEO_START = 70409; // //观看视频开始时间
	public static Object CMD_GAME_GAMEUSER_ADVIDEO_START(RequestParam clientParam) throws Exception {
		CSGameGameuserAdvideoGetRewardRequest request = CSGameGameuserAdvideoGetRewardRequest.parseFrom(clientParam.getData());
		CSGameGameuserAdvideoGetRewardResponse.Builder response = CSGameGameuserAdvideoGetRewardResponse.newBuilder();
		long userId = clientParam.getUserId();

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserAdvideo userAdvideo = GameUser.getUserAdvideo(userId);
		userAdvideo.putAdStartTime(TimeUtils.getCurTime());
		String adcode = UUID.randomUUID().toString();//生成唯一码
		userAdvideo.putAdCode(adcode);
		userAdvideo.update();
		ProtoDataUtils.updatePBUserData(pbUserData, userAdvideo);

		return response;
	}


	// CMD_GAME_GAMEUSER_ADVIDEO_GET_REWARD = 70410; // 领取广告奖励
	public static Object CMD_GAME_GAMEUSER_ADVIDEO_GET_REWARD(RequestParam clientParam) throws Exception {
		CSGameGameuserAdvideoGetRewardRequest request = CSGameGameuserAdvideoGetRewardRequest.parseFrom(clientParam.getData());
		CSGameGameuserAdvideoGetRewardResponse.Builder response = CSGameGameuserAdvideoGetRewardResponse.newBuilder();
		long userId = clientParam.getUserId();

		int type = request.getType();
		int adVideoId = request.getAdVideoId();
		String adCode = request.getAdCode();

		UserAdvideo userAdvideo = GameUser.getUserAdvideo(userId);
		if (!GameUser.checkAdVideo(userAdvideo, adCode)) {// 观看时间不足，或是唯一码不对
			return ErrorWord.WRONG_STATUS;
		}

		List<RewardItem> rewardItemList = new ArrayList<>();
		if (type == AdvideoManager.ADVIDEO_TYPE_1) {//观看广告的奖励配置在iap_gift表
			IapGift iapGift = IapManager.getIapGift(adVideoId);
			if (iapGift == null || iapGift.getIapId() != AdvideoManager.ADVIDEO_CODE || Tool.isEmpty(iapGift.getReward())) {
				return ErrorWord.NOT_DATA;
			}

			if (iapGift.getLimitNum() > 0) {// 每日有限制次数
				int num = userAdvideo.takeDayNum(type, adVideoId);
				if (num + 1 > iapGift.getLimitNum()) {
					return ErrorWord.ALREADY_MAX;// 达到次数上限
				}
			}

			rewardItemList = CommonUtils.takeReawrdItemFromStr(iapGift.getReward());// 获得的奖励
		}

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		userAdvideo.addDayNum(type, adVideoId);// 更新次数
		userAdvideo.putAdCode("");
		userAdvideo.putAdStartTime(0);
		userAdvideo.update();
		ProtoDataUtils.updatePBUserData(pbUserData, userAdvideo);

		if (rewardItemList.size() > 0) {
			RewardManager.addReward(userInfo, rewardItemList, pbUserData, LogType.SYSTEM_AD_VIDEO_REWARD, adVideoId);
		}
		if (type == AdvideoManager.ADVIDEO_TYPE_2) {// 观看广告的再获得一份离线奖励
			UserAffair userAffair = GameUser.getUserAffair(userId);
			if (userAffair.getOfflineGoldNum() > 0) {
				RewardManager.addReward(userInfo, ItemId.GOLD, userAffair.getOfflineGoldNum(), pbUserData, LogType.BUILD_EARN_OFFLINE);
				userAffair.putOfflineGoldNum(0);
				userAffair.update();
			}
		}

		return response;
	}


	// CMD_GAME_GAMEUSER_DECORATE_TITLE_ACTIVE = 70411; // 玩家激活使用称号
	public static Object CMD_GAME_GAMEUSER_DECORATE_TITLE_ACTIVE(RequestParam clientParam) throws Exception {
		CSGameGameuserDecorateTitleActiveRequest request = CSGameGameuserDecorateTitleActiveRequest.parseFrom(clientParam.getData());
		CSGameGameuserDecorateTitleActiveResponse.Builder response = CSGameGameuserDecorateTitleActiveResponse.newBuilder();
		long userId = clientParam.getUserId();
		int decorateId = request.getDecorateId();


		DecorateMain decorateMain = GameBaseData.getDecorateMain(decorateId);
		if (decorateMain == null || decorateMain.getType() != SystemConstant.DECORATE_TYPE_3) {
			return ErrorWord.NOT_DATA;// 不是称号不能激活
		}

		UserDecorate userDecorate = GameDataManager.getUserDecorate(userId, decorateId);
		if (userDecorate == null || userDecorate.getNum() < 1) {
			return ErrorWord.ITEM_LACK;// 未获得该称号
		}

		UserTitle userTitle = GameDataManager.getUserTitle(userId, decorateId);
		long curTime = TimeUtils.getCurTime();
		if (userTitle != null && !userTitle.isExpired(curTime)) {
			return ErrorWord.REPEATED_OPERATION;// 已经激活过,且未过期,同个称号只能同时只激活一个
		}

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		userDecorate.subNum(userInfo, 1, LogType.TITLE_ACTIVE);
		userDecorate.update();
		if (userDecorate.getNum() <= 0) {// 只有称号可以重复获得，全部使用完，通知客户端进行删除
			pbUserData.getSystemBuilder().putDecotateList(userDecorate.getDecorateId(), PBUserDecorate.getDefaultInstance());
		} else {
			ProtoDataUtils.updatePBUserData(pbUserData, userDecorate);
		}

		if (userTitle == null) {
			userTitle = new UserTitle();
			userTitle.putUserId(userId);
			userTitle.putDecorateId(decorateId);
			userTitle.putActiveTime(curTime);
			userTitle.doCreate();
			ProtoDataUtils.updatePBUserData(pbUserData, userTitle, true);
		} else {
			userTitle.putActiveTime(curTime);
			userTitle.update();
			ProtoDataUtils.updatePBUserData(pbUserData, userTitle);
		}

		// 这个称号是对战力或是城市收益的加成效果
		if (decorateMain.getEffectValue() > 0) {
			UserPower userPower = GameUser.getUserPower(userId);
			if (decorateMain.getEffectType() == SystemConstant.DECORATE_TITLE_EFFECT_TYPE_1) {// 干员战力加成百分比
				int newValue = userPower.getPowerAddTitlePer() + decorateMain.getEffectValue();
				userPower.putPowerAddTitlePer(newValue);
				List<UserPartner> partnerList =  userPower.takeUserPartnerList(0);
				PartnerManager.batchUpdatePartnerPower(pbUserData, userInfo, userPower, partnerList);
			}
			if (decorateMain.getEffectType() == SystemConstant.DECORATE_TITLE_EFFECT_TYPE_2) {// 城市总收益加成百分比
				int newValue = userPower.getEarnAddTitlePer() + decorateMain.getEffectValue();
				userPower.putEarnAddTitlePer(newValue);
				List<UserBuild> buildList = userPower.takeUserBuildList(0);
				BuildManager.batchUpdateBuildEarn(pbUserData, userInfo, userPower, buildList);
			}
			if (decorateMain.getEffectType() == SystemConstant.DECORATE_TITLE_EFFECT_TYPE_3) {// 干员战力加成固定值
				int newValue = userPower.getPowerAddTitleCv() + decorateMain.getEffectValue();
				userPower.putPowerAddTitleCv(newValue);
				List<UserPartner> partnerList =  userPower.takeUserPartnerList(0);
				PartnerManager.batchUpdatePartnerPower(pbUserData, userInfo, userPower, partnerList);
			}
		}

		return response;
	}


	// CMD_GAME_GAMEUSER_CHECK_PARTNER_PHOTO = 70412; // 查看某个玩家的当前的战力快照
	public static Object CMD_GAME_GAMEUSER_CHECK_PARTNER_PHOTO(RequestParam clientParam) throws Exception {
		CSGameGameuserCheckPartnerPhotoRequest request = CSGameGameuserCheckPartnerPhotoRequest.parseFrom(clientParam.getData());
		CSGameGameuserCheckPartnerPhotoResponse.Builder response = CSGameGameuserCheckPartnerPhotoResponse.newBuilder();
		long userId = clientParam.getUserId();

		long targetId = request.getTargetId();// 对方的userid
		response.setPartner(PartnerManager.createPartnerPhoto(userId, null));

		return response;
	}
}
